package ru.adhoc.truealarmfree.utils;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.Toast;

import ru.adhoc.truealarmfree.R;
import ru.adhoc.truealarmfree.activities.CancelAlarmBarcode;
import ru.adhoc.truealarmfree.activities.CancelAlarmClassic;
import ru.adhoc.truealarmfree.activities.CancelAlarmText;
import ru.adhoc.truealarmfree.alarmreceiver.AlarmManagerBroadcastReceiver;
import ru.adhoc.truealarmfree.player.SoundPlayer;
import ru.adhoc.truealarmfree.time.TimeHelper;

/**
 * Created by Малюгин Сергей on 10.10.13.
 */
public class Util {

    private static Util instance;
    private Context context;
    private ru.adhoc.truealarmfree.db.DbHelper DbHelper;
    private ru.adhoc.truealarmfree.notification.NfHelper NfHelper;
    private AlarmManagerBroadcastReceiver alarm;

    public Util(Context c) {
        context = c;
        alarm = new AlarmManagerBroadcastReceiver();
        DbHelper = DbHelper.getInstance(context);
        NfHelper = NfHelper.getInstance(context);

    }

    public static Util getInstance(Context ctx){
        if (instance == null){
            instance = new Util(ctx);
        }
        return instance;
    }


    public Intent getActualCancelAlarmIntent(){

        //Получаем настройки отключения
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

        Intent cancelIntent;

        if(sp.getBoolean("TextOff",false)){
            cancelIntent = new Intent(context, CancelAlarmText.class);
        }
        else if(sp.getBoolean("classicOff", false)){
            cancelIntent = new Intent(context, CancelAlarmClassic.class);
        }
        else {
            cancelIntent = new Intent(context, CancelAlarmBarcode.class);
        }
        return cancelIntent;
    }


    public void cancelAlarmUtil(int id){

        Constants.getInstance(context).setAlarmed(false,id);

        //Вырубаем воспроизведение музыки
        SoundPlayer.getInstance(context).stopPlaySound();

        //Вырубаем ресивер
        alarm.CancelAlarm(context,id);

        //Получаем актуальное время нового звонка по ид
        Long newAlarmTime = TimeHelper.getInstance(context).getActualTimeForAlarmByID(id);

        //Обновляем в базе время будильника
        SQLiteDatabase db1 = DbHelper.getWritableDatabase();
        try {
            DbHelper.refreshAlarmTime(db1, newAlarmTime, id);
        }
        finally {
            if(db1 != null)
                db1.close();
        }



        //запускаем ресивер с новым временем
        alarm.SetAlarm(context,newAlarmTime,id);

        //показываем тост
        TimeHelper.getInstance(context).showAlarmToast(newAlarmTime);

        //Обновляем нотификацию
        NfHelper.showNotificationService(0L, false);

        //Сбрасываем счётчик откладываний
        TimeHelper.getInstance(context).currentRepeat = 0;

    }

    public void resetAlarmUtil(int id){
        //Вырубаем мелодию и вибро
        SoundPlayer.getInstance(context).stopPlaySound();
        //вызваем метод для переноса будильника на заданный в настройках интервал
        TimeHelper.getInstance(context).resetAlarmTimeByInterval(id);
        //Делаем тост
        Toast.makeText(context, context.getResources().getText(R.string.transfer).toString()
                + " " + TimeHelper.getInstance(context).currentRepeat
                + " " + context.getResources().getText(R.string.countTransfer).toString(),
                Toast.LENGTH_LONG).show();

    }

    public void restartAlarmsOnBootReceive(){

        SQLiteDatabase db = DbHelper.getWritableDatabase();

        try {
            Cursor c = DbHelper.getActiveAlarms(db);
            if(c.moveToFirst())
                operationsToOnAlarm(c.getLong(c.getColumnIndex("time")),
                        c.getInt(c.getColumnIndex("id")));
            c.close();
        }
        finally {
            if(db != null)
                db.close();
        }

        Log.v("My", "alarms restarted on boot");
    }

    public void operationsToOnAlarm(long actTime, int id){
        //start alarm receiving
        alarm.SetAlarm(context,actTime,id);
        //show alarm toast
        TimeHelper.getInstance(context).showAlarmToast(actTime);
        //show notification
        NfHelper.showNotificationService(0L, false);
    }

    public void operationsToOffAlarm(int id) {
        //stop alarm receiving
        alarm.CancelAlarm(context,id);
        //stop showing alarm notification
        NfHelper.cancelShowNotificationService(false);
        //stop playing alarm sound
        SoundPlayer.getInstance(context).stopPlaySound();
    }

    public int androidVersionCode() {
        if (android.os.Build.VERSION.RELEASE.startsWith("2."))
            return 2;
        else if (android.os.Build.VERSION.RELEASE.startsWith("3.")) {
            return 3;
        } else if (android.os.Build.VERSION.RELEASE.startsWith("4.")) {
            return 4;
        } else {
            return 99;
        }
    }

    public String createRepDaysString(String strRepDays){

        boolean mon = true;
        boolean tue = true;
        boolean wed = true;
        boolean thu = true;
        boolean fri = true;
        boolean sut = true;
        boolean sun = true;

        if(strRepDays.indexOf("0") != -1)
            mon = false;
        if(strRepDays.indexOf("1") != -1)
            tue = false;
        if(strRepDays.indexOf("2") != -1)
            wed = false;
        if(strRepDays.indexOf("3") != -1)
            thu = false;
        if(strRepDays.indexOf("4") != -1)
            fri = false;
        if(strRepDays.indexOf("5") != -1)
            sut = false;
        if(strRepDays.indexOf("6") != -1)
            sun = false;

        //Только выходные:
        if(sut == true && sun == true && mon == false && tue == false && wed == false && thu == false && fri == false)
            return ""+ context.getResources().getText(R.string.weekends);

        //только будние:
        if(sut == false && sun == false && mon == true && tue == true && wed == true && thu == true && fri == true)
            return ""+ context.getResources().getText(R.string.weekdays);

        //каждый день:
        if(sut == true && sun == true && mon == true && tue == true && wed == true && thu == true && fri == true)
            return ""+ context.getResources().getText(R.string.every_day);

        //Остальные вариации:
        String returnString = "";

        if(mon == true)
            returnString = returnString + context.getResources().getText(R.string.mon) +" ";
        if(tue == true)
            returnString = returnString + context.getResources().getText(R.string.tue) +" ";
        if(wed == true)
            returnString = returnString + context.getResources().getText(R.string.wed) +" ";
        if(thu == true)
            returnString = returnString + context.getResources().getText(R.string.thu) +" ";
        if(fri == true)
            returnString = returnString + context.getResources().getText(R.string.fri) +" ";
        if(sut == true)
            returnString = returnString + context.getResources().getText(R.string.sat) +" ";
        if(sun == true)
            returnString = returnString + context.getResources().getText(R.string.sun);

        return returnString;

    }

//Проверка на существование файла по его ури
    public boolean uriFileExist(Uri uri){
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);

        if(cursor == null)
            return false;

        if(cursor.moveToFirst()){
            cursor.close();
            return true;
        }
        else {
            cursor.close();
            return false;
        }

    }

    public void setTheme(LinearLayout LL){

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
        boolean blue = sp.getBoolean("blue_theme", true);
        boolean yellow = sp.getBoolean("yellow_theme", false);
        boolean christmas = sp.getBoolean("christmas_theme", false);

        if(yellow)
            LL.setBackgroundResource(R.drawable.main_activity_gradient_yellow);
        if(blue)
            LL.setBackgroundResource(R.drawable.main_activity_gradient);
        if(christmas)
            LL.setBackgroundResource(R.drawable.christmas_theme);


    }

}
